package com.phone580.app.splash;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.xml.sax.SAXException;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.phone580.app.BaseTask;
import com.phone580.app.CommonData;
import com.phone580.app.entity.UpdateEntity;
import com.phone580.app.model.CheckUpdateModel;
import com.phone580.app.net.HttpAccess;
import com.phone580.app.untilty.CommonUtility;
import com.phone580.app.untilty.ZipUtil;

/**
 * 升级网页data包
 * @author matthew
 *
 */
public class CheckUpdateTask extends BaseTask {
	private String version;
	private static final String DATA_VERSION = "data_version";
	public static final int SUCCESS = 1;
	public static final int FAILD = -1;
	private Handler handler;
	public CheckUpdateTask(Context context, Handler handler) {
		super(context);
		version = CommonUtility.getStoreValue(context, DATA_VERSION);
		this.handler = handler;
	}

	@Override
	public void setParams(Object... params) {

	}

	@Override
	protected Object doInBackground(Void... params) {
		if (version == null || "".equals(version)) {
			version = "0";
		}
//		version = "2";
//		String checkUpdateURL = "http://www.phone580.com:8082/websamp/pubapi/checkupdate?type=FBS_MOBILE_DATA&isPub=0&versioncode=" + version;
		String checkUpdateURL = "http://www.phone580.com:8082/websamp/pubapi/checkupdate?isPub=1&type=FBS_MOBILE_DATA&versioncode=" + version;
		try {
			CheckUpdateModel model = new CheckUpdateModel();
			String result = HttpAccess.doGet(checkUpdateURL);
			UpdateEntity entity = model.parseCheckUpdateStep1(result.trim());
			if (entity != null) {
				if (!entity.getVersionCode().equals(version)) {
					CommonUtility.storeValue(context, DATA_VERSION, entity.getVersionCode());
					byte[] content = downloadXMLFile(entity.getUrlRoot() + entity.getConfigFile());
					if (content.length != 0) {
						String xml = new String(content, "utf-8");
						xml = xml.substring(xml.indexOf("<"), xml.lastIndexOf(">") + 1);//replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", "").trim();
						String name = model.parseCheckUpdateStep2(xml);
						if (name != null) {
							String zipFile = CommonData.APP_PATH + "data.zip";
							String unZipFilePath = CommonData.APP_PATH + "data";
							CommonUtility.storeValue(context, "dataURL", entity.getUrlRoot() + name);
							downloadDataFile(entity.getUrlRoot() + name, zipFile);
							File file = new File(unZipFilePath);
							if (!file.exists()) {
								file.mkdirs();
							}
							handler.sendEmptyMessage(SplashActivity.UNZIP_FILE_FLAG);
							ZipUtil.upZipFile(zipFile, unZipFilePath);
							return SUCCESS;
						}
					}	 
				} else {
					String zipFile = CommonData.APP_PATH + "data.zip";
					String unZipFilePath = CommonData.APP_PATH + "data";
					File zip = new File(zipFile);
					if (!zip.exists()) {
						String url = CommonUtility.getStoreValue(context, "dataURL");
						downloadDataFile(url, zipFile);
					}
					File file = new File(unZipFilePath);
					if (!file.exists()) {
						file.mkdirs();
					}
					handler.sendEmptyMessage(SplashActivity.UNZIP_FILE_FLAG);
					ZipUtil.upZipFile(zipFile, unZipFilePath);
					return SUCCESS;
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return FAILD;
	}
	
	private byte[] downloadXMLFile(String url) throws IOException {
		URL httpurl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection)httpurl.openConnection();
		int size = connection.getContentLength();
		byte[] b = new byte[4096];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		InputStream in = connection.getInputStream();
		int t = 0;
		while ((len = in.read(b, 0, b.length)) != -1) {
			t += len;
			Message msg = new Message();
			msg.what = SplashActivity.DOWNLOAD_CONFIG_FLAG;
			msg.arg1 = (int)((t / (float)size) * 100);
			handler.sendEmptyMessage(SplashActivity.DOWNLOAD_CONFIG_FLAG);
			bos.write(b, 0, len);
		}
		connection.disconnect();
		byte[] data = bos.toByteArray();
		bos.close();
		return data;
	}
	
	private void downloadDataFile(String url, String path) throws IOException {
		URL httpurl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection)httpurl.openConnection();
		int size = connection.getContentLength();
		byte[] b = new byte[10240];
		FileOutputStream fos = new FileOutputStream(path);
		int len = 0;
		InputStream in = connection.getInputStream();
		int t = 0;
		while ((len = in.read(b, 0, b.length)) != -1) {
			t += len;
			Message msg = new Message();
			msg.what = SplashActivity.DOWNLOAD_DATA_FLAG;
			msg.arg1 = (int)((t / (float)size) * 100);
			handler.sendMessage(msg);
			fos.write(b, 0, len);
		}
		fos.close();
		connection.disconnect();
	}

}
